<template>
  <div class="pre-book-edit">
    <!-- 编辑弹窗 -->
    <el-drawer
      title="课程预约"
      :visible.sync="dialogVisible"
      :wrapperClosable="false"
      :close-on-press-escape="false"
      :direction="direction"
      :before-close="handleClose">
      <div class="dialog-body" v-loading="dialogLoading">
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="120px"
          class="demo-ruleForm">
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="预约会员" prop="memberUserId">
                <el-select v-model="ruleForm.memberUserId" filterable placeholder="请选择" style="width:100%" clearable @change="changeMember" :disabled="$parent.actionType == 'edit'">
                  <el-option
                    v-for="item in memberArr"
                    :key="item.userId"
                    :label="item.userName"
                    :value="item.userId">
                    <span style="float: left">{{ item.userName }}</span>
                    <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="签约课程" prop="signCourseId">
                <el-select v-model="ruleForm.signCourseId" filterable placeholder="请选择" style="width:100%" clearable @change="changeSignCourse" :disabled="$parent.actionType == 'edit'">
                  <el-option
                    v-for="item in ccourseArr"
                    :key="item.id"
                    :label="item.courseName"
                    :value="item.id">
                    <span style="float: left">{{ item.courseName }}</span>
                    <span style="float: right; color: #8492a6; font-size: 13px">{{ item.id }}<em v-if="item.saleMode">({{ setSaleMode(item.saleMode)}})</em></span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="选择教练" prop="teachCoachUserId">
                <el-select v-model="ruleForm.teachCoachUserId" filterable placeholder="请选择" style="width:100%" clearable :disabled="$parent.actionType == 'edit'">
                  <el-option
                    v-for="item in coachArr"
                    :key="item.id"
                    :label="item.userName"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="课程时间" prop="classStartDate">
                <el-date-picker
                  v-model="ruleForm.classStartDate"
                  value-format="yyyy-MM-dd"
                  style="width: 49%"
                  type="date"
                  :disabled="$parent.actionType == 'edit'"
                  placeholder="选择日期">
                </el-date-picker>
                <el-time-select
                  v-model="ruleForm.classStartDateTime"
                  style="width: 49%"
                  :picker-options="{
                    start: '00:00',
                    step: '00:30',
                    end: '23:30'
                  }"
                  :disabled="$parent.actionType == 'edit'"
                  placeholder="选择时间">
              </el-time-select>
              </el-form-item>
            </el-col>
            <el-col :span="24" v-if="$parent.actionType == 'edit'">
              <el-form-item label="签约状态" prop="appointmentStatus">
                <el-input v-model="appointmentStatus" :disabled="true"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24" v-if="$parent.actionType == 'edit' && appointmentStatus == '已完成'">
              <el-form-item label="核销码" prop="qrcode">
                <el-input v-model="qrcode" :disabled="true" style="margin-bottom: 10px;"></el-input>
                <p><el-button type="primary" style="margin-left: 10px;" @click="appointmentCancel" v-hasPermission="permission.resetPassword">作废</el-button></p>
              </el-form-item>
            </el-col>
            <el-col :span="24" v-if="$parent.actionType == 'edit' && appointmentStatus == '已预约'">
              <el-form-item label="">
                <el-button type="primary" @click="writeOffAppointment" v-if="userInfo.roleCode == 'ADMIN'">核销签课</el-button>
                <el-button type="warning" @click="disAppointment" v-hasPermission="permission.edit">取消预约</el-button>
                <p style="margin-top: 20px;"><canvas id="qrcodeDom"></canvas></p>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button @click="confirmDialog" type="primary" :disabled="$parent.actionType == 'edit'" v-if="$parent.actionType != 'edit'">确定</el-button>
      </div>
    </el-drawer>
  </div>
</template>
<script>
import {mapGetters} from 'vuex'
import cvueDialog from '@/components/cvue-dialog'
import QRCode from 'qrcode'
import {baseServer} from '@/config/config'
export default {
  name: 'pre-book-edit',
  components: {
    cvueDialog
  },
  data () {
    return {
      ruleForm: {
        signCourseId: '',
        teachCoachUserId: '',
        classStartDate: '',
        classStartDateTime: '',
        memberUserId: ''
      },
      rules: {
        signCourseId: [
          { required: true, message: '请选择课程', trigger: 'blur' }
        ],
        teachCoachUserId: [
          { required: true, message: '请选择教练', trigger: 'blur' }
        ],
        classStartDate: [
          { required: true, message: '请选择日期', trigger: 'blur' }
        ],
        classStartDateTime: [
          { required: true, message: '请选择时间', trigger: 'blur' }
        ],
        memberUserId: [
          { required: true, message: '请选择会员', trigger: 'blur' }
        ]
      },
      disabled: false,
      dialogLoading: false,
      direction: 'rtl',
      ccourseArr: [],
      coachArr: [],
      memberArr: [],
      appointmentStatus: '',
      qrcode: ''
    }
  },
  mounted () {
    this.getMemberList()
    // console.log(this.userInfo)
  },
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    title () {
      var title = ''
      if (this.$parent.actionType == 'add') {
        title = '新增'
      } else {
        title = '编辑'
      }
      return title
    },
    ...mapGetters(['token', 'userInfo'])
  },
  methods: {
    setSaleMode (val) {
      if (val === 0) {
        return '按次'
      } else if (val === 1) {
        return '包时'
      } else {
        return ''
      }
    },
    getQRCode (data) {
      let opts = {
        errorCorrectionLevel: 'H', // 容错级别
        type: 'image/png', // 生成的二维码类型
        quality: 0.3, // 二维码质量
        margin: 0, // 二维码留白边距
        width: 100, // 宽
        height: 80, // 高
        // text: 'http://www.xxx.com', // 二维码内容
        color: {
          dark: '#333333',
          light: '#fff'
        }
      }
      let qrDom = document.getElementById('qrcodeDom')
      QRCode.toCanvas(qrDom, data, opts, function (error) {
        JSON.stringify(error)
      })
    },
    setAppointmentStatus (val) {
      if (val === -1) {
        return '已作废'
      } else if (val === 0) {
        return '已预约'
      } else if (val === 1) {
        return '已完成'
      } else if (val === 2) {
        return '会员取消'
      } else if (val === 3) {
        return '教练取消'
      }
    },
    getMemberList () {
      var params = {
        current: 1,
        size: 10000,
        key: '',
        type: ''
      }
      this.dialogLoading = false
      this.$store.dispatch('manage/MemberPageGet', params).then(res => {
        // console.log(res)
        if (res.code == '200') {
          var data = res.data.records
          this.memberArr = data
          this.getEditDetail()
        }
        this.dialogLoading = false
      }).catch(err => {
        console.log(err)
        this.dialogLoading = false
      })
    },
    changeMember (val) {
      // console.log(val)
      this.memberArr.forEach((item, index) => {
        if (item.userId == val) {
          this.getSignCourseList(item.phone)
        }
      })
      this.$set(this.ruleForm, 'signCourseId', '')
      this.$set(this.ruleForm, 'teachCoachUserId', '')
      this.coachArr = []
    },
    // 课程接口
    getSignCourseList (key) {
      var params = {
        'size': 1000,
        'current': 1,
        'payTimeStart': '',
        'payTimeEnd': '',
        'signCourseStates': [1, 2], //  
        'courseType': 1, // 1 私教课
        'teachCoachUserId': '',
        'key': key,
        'ext': {},
        'orders': [
          {
            'order': 'desc',
            'sort': 'createTime'
          }
        ]
      }
      this.$store.dispatch('manage/SignPage', params).then(res => {
        console.log(res)
        if (res.code == '200') {
          var data = res.data.records
          this.ccourseArr = data
        }
      })
    },
    changeSignCourse (val) {
      // console.log(val)
      this.getCourseDetail(val)
      this.$set(this.ruleForm, 'teachCoachUserId', '')
    },
    getCourseDetail (val) {
      var params = {
        id: val
      }
      this.$store.dispatch('manage/SignGet', params).then(res => {
        // console.log(res)
        if (res.code == 200) {
          var data = res.data
          this.coachArr = data.teachCoachUsers
          // console.log(this.coachArr)
        }
      }).catch(err => {
        console.log(err)
      })
    },
    // 触发事件
    handleClose () {
      this.$emit('handleClose')
    },
    closeDialog () {
      this.$emit('closeDialog')
    },
    confirmDialog () {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          var params = {
            // id: this.$parent.actionType == 'add' ? '' : this.$parent.rowData.id,
            'classStartTime': this.ruleForm.classStartDate + ' ' + this.ruleForm.classStartDateTime + ':00',
            'memberUserId': this.ruleForm.memberUserId,
            'signCourseId': this.ruleForm.signCourseId,
            'teachCoachUserId': this.ruleForm.teachCoachUserId
          }
          this.dialogLoading = true
          var url = this.$parent.actionType == 'add' ? 'manage/CoachOrderAdd' : 'manage/CoachOrderAdd'
          this.$store.dispatch(url, params).then(res => {
            // console.log(res)
            if (res.code == '200') {
              this.$message({
                message: res.msg,
                duration: 2000,
                type: 'success'
              })
              this.$emit('confirmDialog')
            } else {
              this.$message({
                message: res.msg,
                duration: 2000,
                type: 'error'
              })
            }
            this.dialogLoading = false
          }).catch(err => {
            console.log(err)
            this.dialogLoading = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    getDetail () {
    },
    getEditDetail () {
      // console.log(this.$parent.rowData)
      if (this.$parent.actionType == 'edit') {
        this.$set(this.ruleForm, 'memberUserId', this.$parent.rowData.memberUserId)
        this.changeMember(this.$parent.rowData.memberUserId)
        this.$set(this.ruleForm, 'signCourseId', this.$parent.rowData.signCourseId)
        this.changeSignCourse(this.$parent.rowData.signCourseId)
        this.$set(this.ruleForm, 'teachCoachUserId', this.$parent.rowData.coachUserId)
        this.$set(this.ruleForm, 'classStartDate', this.$parent.rowData.classStartTime.split(' ')[0])
        this.$set(this.ruleForm, 'classStartDateTime', this.$parent.rowData.classStartTime.split(' ')[1])
        this.appointmentStatus = this.setAppointmentStatus(this.$parent.rowData.appointmentStatus) 
        this.$nextTick(() => {
          var url = baseServer + '/' + this.$parent.rowData.id
          console.log(url)
          this.getQRCode(url)
        })
      }
    },
    // 作废
    appointmentCancel () {
      this.$confirm('确定要作废吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var params = {
          id: this.$parent.rowData.id
        }
        this.$store.dispatch('manage/AppointmentCancel', params).then(res => {
          this.$message({
            type: 'success',
            message: res.msg
          })
        })
      }).catch(() => {
      })
    },
    // 取消预约
    disAppointment () {
      this.$confirm('确定要取消预约吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var params = {
          id: this.$parent.rowData.id
        }
        this.$store.dispatch('manage/DisAppointment', params).then(res => {
          this.$message({
            type: 'success',
            message: res.msg
          })
        })
      }).catch(() => {
      })
    },
    // 核销
    writeOffAppointment () {
      this.$confirm('确定要核销吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var params = {
          id: this.$parent.rowData.id
        }
        this.$store.dispatch('manage/WriteOffAppointment', params).then(res => {
          this.$message({
            type: 'success',
            message: res.msg
          })
        })
      }).catch(() => {
      })
    }
  }
}
</script>
<style lang="scss">
.pre-book-edit{
  .el-drawer__header{
    margin-bottom: 17px !important;
    padding: 20px 20px 15px !important;
    border-bottom: 1px solid #eee !important;
  }
  .dialog-footer{
    position: absolute;
    text-align: right;
    z-index: 10;
    bottom: 0;
    right: 0;
    border-top: 1px solid #eee;
    width: 100%;
    height: 50px;
    line-height: 50px;
    padding-right: 30px;
    box-sizing: border-box;
  }
  .dialog-body{
    padding: 0 30px 0 0;
  }
}
</style>
